<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\service\goods;

use app\common\model\GoodsSpec;
use app\common\model\GoodsSpecRelation;
use app\common\model\Goods;
use think\facade\Db;

class SpecService
{
    /**
     * 获取规格列表
     */
    public function getSpecList($where = [], $limit = 15)
    {
        return GoodsSpec::withSearch(array_keys($where), $where)
            ->order('id desc')
            ->paginate($limit);
    }

    /**
     * 添加或编辑规格
     */
    public function saveSpec($data)
    {
        try {
            if (isset($data['id']) && $data['id']) {
                $spec = GoodsSpec::findOrFail($data['id']);
                $spec->save(['name' => $data['name'], 'rule_value' => $data['rule_value'], 'status' => $data['status'] ?? 1]);
            } else {
                $spec = new GoodsSpec;


                $spec->save([
                    'name'       => $data['name'],
                    'rule_value' => $data['rule_value'],
                    'status'     => $data['status'] ?? 1
                ]);
            }
        } catch (\Exception $e) {
            throw new \Exception('添加或编辑规格失败: ' . $e->getMessage());
        }

        return $spec;
    }

    /**
     * 删除规格
     */
    public function deleteSpec($id)
    {
        // 检查是否有商品使用该规格
        try {
            $count = GoodsSpecRelation::where('spec_id', $id)->count();
            if ($count > 0) {
                throw new \Exception('该规格已被商品使用，无法删除');
            }

            return GoodsSpec::destroy($id);
        } catch (\Exception $e) {
            throw new \Exception('删除规格失败: ' . $e->getMessage());
        }
    }

    /**
     * 保存商品规格关联
     */
    public function saveGoodsSpec($goods_id, $spec_data)
    {
        // 先删除旧的关联
        GoodsSpecRelation::where('goods_id', $goods_id)->delete();

        if (empty($spec_data)) {
            return true;
        }

        $data = [];
        foreach ($spec_data as $item) {
            $data[] = [
                'goods_id'   => $goods_id,
                'spec_id'    => $item['spec_id'],
                'spec_value' => $item['spec_value'],
            ];
        }

        return (new GoodsSpecRelation)->saveAll($data);
    }

    /**
     * 获取商品的规格信息
     */
    public function getGoodsSpecInfo($goods_id)
    {
        // 获取商品规格关联
        $relations = Db::table('goods_spec_relation')
            ->alias('r')
            ->join('goods_spec s', 'r.spec_id = s.id')
            ->where('r.goods_id', $goods_id)
            ->field('r.spec_id, r.spec_value, s.name as spec_name, s.rule_value')
            ->select();

        $result = [];
        foreach ($relations as $relation) {
            // 直接解析JSON字段
            $rule_value = json_decode($relation['rule_value'], true);
            $spec_value = json_decode($relation['spec_value'], true);

            $result[] = [
                'spec_id'    => $relation['spec_id'],
                'spec_name'  => $relation['spec_name'],
                'rule_value' => $rule_value,
                'spec_value' => $spec_value
            ];
        }

        return $result;
    }

    /**
     * 按规格筛选商品
     * @param array $spec_filters 规格筛选条件，格式：['字段名' => '字段值', ...]
     * @param array $other_where 其他筛选条件
     * @param int $limit 分页大小
     * @return \think\Paginator
     */
    public function filterGoodsBySpec($spec_filters, $other_where = [], $limit = 15)
    {
        if (empty($spec_filters)) {
            // 没有规格筛选条件，直接返回商品列表
            return Goods::withSearch(array_keys($other_where), $other_where)
                ->order('id desc')
                ->paginate($limit);
        }

        // 获取符合规格筛选条件的商品ID
        $query = GoodsSpecRelation::where(function ($query) use ($spec_filters) {
            foreach ($spec_filters as $field => $value) {
                // 使用JSON查询语法筛选
                $query->where("JSON_EXTRACT(spec_value, '$.{$field}') = :value", ['value' => $value]);
            }
        });

        $goods_ids = $query->column('goods_id');

        if (empty($goods_ids)) {
            // 没有符合条件的商品，返回空结果
            return Goods::where('id', 0)->paginate($limit);
        }

        // 获取商品列表
        return Goods::withSearch(array_keys($other_where), $other_where)
            ->whereIn('id', $goods_ids)
            ->order('id desc')
            ->paginate($limit);
    }

    /**
     * 验证规格并提取值
     */
    public function validateSpecForGood($spec_id)
    {
        try {
            $spec = GoodsSpec::find($spec_id);
            if (!$spec) {
                throw new \Exception('规格不存在');
            }

            // 直接从数据库获取原始JSON数据
            $row        = Db::table('goods_spec')->where('id', $spec_id)->find();
            $rule_value = json_decode($row['rule_value'], true);

            return [
                'spec_id'    => $spec->getData('id'),
                'spec_name'  => $spec->getData('name'),
                'rule_value' => $rule_value
            ];
        } catch (\Exception $e) {
            throw new \Exception('获取规格信息失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取所有可筛选的规格字段
     */
    public function getAllFilterFields()
    {
        try {
            // 直接从数据库获取规格列表
            $specs = Db::table('goods_spec')
                ->where('status', 1)
                ->field('id, name, rule_value')
                ->order('id desc')
                ->select();

            $fields = [];
            foreach ($specs as $spec) {
                $rule_value = json_decode($spec['rule_value'], true);

                foreach ($rule_value as $field) {
                    // 只返回可用于筛选的字段（select类型）
                    if ($field['type'] == 'select' && !empty($field['detail'])) {
                        $fields[] = [
                            'spec_id'     => $spec['id'],
                            'spec_name'   => $spec['name'],
                            'field_name'  => $field['value'],
                            'field_label' => $field['label'],
                            'options'     => $field['detail']
                        ];
                    }
                }
            }

            return $fields;
        } catch (\Exception $e) {
            throw new \Exception('获取可筛选字段失败: ' . $e->getMessage());
        }
    }

    /**
     * 更新规格状态
     */
    public function updateSpecStatus($id, $status)
    {
        try {
            $spec = GoodsSpec::find($id);
            if (!$spec) {
                throw new \Exception('规格不存在');
            }

            $spec->status = $status;
            return $spec->save();
        } catch (\Exception $e) {
            throw new \Exception('更新规格状态失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取规格详情
     */
    public function getSpecDetail($id)
    {
        try {
            $spec = GoodsSpec::find($id);
            if (!$spec) {
                throw new \Exception('规格不存在');
            }

            return $spec;
        } catch (\Exception $e) {
            throw new \Exception('获取规格详情失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取所有可用规格
     */
    public function getAvailableSpecs()
    {
        try {
            // 直接从数据库获取规格列表
            $specs = Db::table('goods_spec')
                ->where('status', 1)
                ->field('id, name, rule_value')
                ->order('id desc')
                ->select();

            // 处理每个规格的rule_value
            $result = [];
            foreach ($specs as $spec) {
                $rule_value = json_decode($spec['rule_value'], true);

                $result[] = [
                    'id'         => $spec['id'],
                    'name'       => $spec['name'],
                    'rule_value' => $rule_value
                ];
            }

            return $result;
        } catch (\Exception $e) {
            throw new \Exception('获取可用规格列表失败: ' . $e->getMessage());
        }
    }
}